package com.sg.business.projectgroup.handler;

import java.util.Iterator;
import java.util.Map;

import org.eclipse.core.commands.Command;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.ui.IWorkbenchPart;

import com.mobnut.db.model.IContext;
import com.mobnut.db.model.PrimaryObject;
import com.sg.business.model.Project;
import com.sg.business.model.ProjectGroup;
import com.sg.business.resource.nls.Messages;
import com.sg.widgets.MessageUtil;
import com.sg.widgets.command.AbstractNavigatorHandler;
import com.sg.widgets.commons.selector.NavigatorSelector;
import com.sg.widgets.part.CurrentAccountContext;
import com.sg.widgets.viewer.ViewerControl;

public class ImportProjectOfProjectGroup extends AbstractNavigatorHandler {

	private static final String NAVIID = "projectgroup.project.selector";
	private static final String TITLE = Messages.get().SelectAddtionProject;

	@Override
	protected void execute(PrimaryObject selected, IWorkbenchPart part,
			final ViewerControl vc, Command command, Map<String, Object> parameters,
			IStructuredSelection selection) {
		final ProjectGroup master = (ProjectGroup) vc.getMaster();
		NavigatorSelector n = new NavigatorSelector(NAVIID, TITLE) {
			@Override
			protected void doOK(IStructuredSelection is) {
				if (is != null && !is.isEmpty()
						&& is.getFirstElement() instanceof Project) {
					try {
						Iterator<?> iter = is.iterator();
						while (iter.hasNext()) {
							Object next = iter.next();
							doImportProject(master, (Project) next);
						}
						vc.doReloadData();
						super.doOK(is);
					} catch (Exception e) {
						MessageUtil.showToast(e);
					}

				} else {
					MessageUtil.showToast(Messages.get().SelectAddtionProject, SWT.ICON_WARNING);
				}
			}

		};
		n.setMaster(master);
		n.show();
	}

	private void doImportProject(ProjectGroup projectGroup, Project project)
			throws Exception {
		IContext context = new CurrentAccountContext();
		projectGroup.doAddProject(context, project.get_id());
	}

	@Override
	protected boolean nullSelectionContinue(IWorkbenchPart part,
			ViewerControl vc, Command command) {
		return true;
	}

}
